﻿using Microsoft.Extensions.Logging;
using Renci.SshNet.Common;
using Renci.SshNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FunArts.EasyDevOps.Rcl.Repertories;
using FunArts.EasyDevOps.Shared.Models.SshClient.KeepAlivedClient;
using FunArts.EasyDevOps.Rcl.Repertories.Impl;
using FunArts.EasyDevOps.Shared.Models.Enums;
using FunArts.EasyDevOps.Shared.Models.SshClient.Command;
using static Org.BouncyCastle.Math.EC.ECCurve;

namespace FunArts.EasyDevOps.Rcl.Service.Impl
{
    public class RemoteKeepAlivedService: IRemoteKeepAlivedService
    {
        public ISshClientService SshClientService { get; set; }
        public IKeepalivedConfigRepository KeepalivedConfigRepository { get; set; }

        public RemoteKeepAlivedService(ISshClientService sshClientService, IKeepalivedConfigRepository keepalivedConfigRepository)
        {
            SshClientService = sshClientService;
            KeepalivedConfigRepository = keepalivedConfigRepository;
        }
        // 配置路径常量
        private const string KeepalivedConfigPath = "/etc/keepalived/keepalived.conf";
        private const string KeepalivedServiceName = "keepalived";

        
        /// <summary>
        /// 获取 Keepalived 配置文件内容
        /// </summary>
        public KeepalivedConfig GetKeepalivedConfig()
        {
            var confByte = SshClientService.DownloadFile(KeepalivedConfigPath);
            if (confByte == null)
            {
                return new KeepalivedConfig();
            }
            var confStr = Encoding.UTF8.GetString(confByte);
            return KeepalivedConfigRepository.Parse(confStr);
        }

        /// <summary>
        /// 更新 Keepalived 配置
        /// </summary>
        public async Task UpdateKeepalivedConfig(KeepalivedConfig keepalivedConfig, Action<double> progressCallback = null)
        {
            var configText = KeepalivedConfigRepository.Generate(keepalivedConfig);

            //上传文件
            await SshClientService.UploadFileAsync(Encoding.UTF8.GetBytes(configText), KeepalivedConfigPath, progressCallback);
            
            //设置文件权限
            RootFileCommand rootFileCommand = new RootFileCommand
            {
                FileName = KeepalivedConfigPath
            };
            var linuxCommandResult = SshClientService.ExecuteCommand(rootFileCommand);

            KeepAlivedCommand keepAlivedCommand = new KeepAlivedCommand
            {
                KeepAlivedCommandType = KeepAlivedCommandTypeEnum.Reload
            };
            SshClientService.ExecuteCommand(keepAlivedCommand);
            keepAlivedCommand.KeepAlivedCommandType = KeepAlivedCommandTypeEnum.Restart;
            SshClientService.ExecuteCommand(keepAlivedCommand);
        }
    }
}
